import asyncio
import json
import threading
import yuanye as yy
from PyQt5 import QtGui
from PyQt5.QtCore import QThread, pyqtSignal, QSize, Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QWidget, QMessageBox, QListWidgetItem
from websocket import create_connection
from ui.form_main import Ui_Form

IP = '10.12.59.59'
PORT = '8088'
head_icon = 'icon/boy_48.png'


class MainView(QWidget, Ui_Form):

    def __init__(self, info):
        super(MainView, self).__init__()
        self.setupUi(self)
        print('info', info)
        self.cid = info['cid']
        self.name = info['name']
        self.contacts = info['contact']
        self.messageCache = yy.MessageCache()
        self.current_index = -1
        self.desId = -1
        self.initView()

        self.client = yy.YClient(IP, PORT)
        self.client.handshake(self.cid)
        self.client.startReceiveMessage(self.dealMessage)

    def initView(self):
        png = QPixmap(head_icon)
        png.scaled(30, 30)
        self.label_2.setPixmap(png)
        self.label_3.setText(self.cid)
        self.label_4.setText(self.name)
        self.listWidget.clicked.connect(self.checkItem)
        for c in self.contacts:
            self.listWidget.addItem(QListWidgetItem(c[1]))

    def checkItem(self, index):
        self.current_index = index.row()
        self.desId = self.contacts[self.current_index][0]
        print(self.current_index, type(self.desId), self.desId)
        self.updateChatView()

    def updateChatView(self):
        self.label.setText(self.contacts[self.current_index][1])
        messages = self.messageCache.getMessages(self.desId)
        print(type(messages), messages)
        if messages:
            for msg in messages:
                item = QListWidgetItem(msg.content())
                if msg.isMine():
                    item.setTextAlignment(Qt.AlignRight)
                self.listWidget_2.addItem(item)
        else:
            self.listWidget_2.clear()

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        self.client.close()

    def dealMessage(self, msg):
        print(msg)
        ym = yy.YMessage(msg)
        if ym.isSys():
            if ym.getCode() == 400:
                QMessageBox.information(self, '下线提醒', '有其他客户端登录，您被挤占下线了', QMessageBox.Yes)
                self.close()
            else:
                self.label_5.setText('已上线')
        elif ym.isChat():
            desId = ym.getSrcId()
            text = ym.getText()
            # 保存信息到消息缓存
            self.messageCache.append(desId, False, text)
            print(type(self.messageCache), self.messageCache)
            if desId == self.desId:
                self.listWidget_2.addItem(QListWidgetItem(text))

    def send(self):
        info = self.textEdit.toPlainText()
        # 保存信息到消息缓存
        self.messageCache.append(self.desId, True, info)
        print(self.messageCache.getMessages(self.desId))
        # 更新当前信息列表UI
        item = QListWidgetItem(info)
        item.setTextAlignment(Qt.AlignRight)
        self.listWidget_2.addItem(item)
        self.textEdit.clear()
        # 发送消息到服务器
        self.client.send(self.cid, self.desId, info)


